#!/bin/sh
#
# description: Starts and stops the moServices core 
#
mos=/usr/local/etc/mos/core
spa=/usr/local/etc/dvdplayer/savedrss/scripts

case "$1" in
  start)
	echo "Starting core..."
	if [ ! -d /tmp/www/mos ] ; then
		[ -f /tmp/www/index.html ] && mv /tmp/www/index.html /tmp/www/WebTorrentHome.html
		echo "  Copying files..."
		cp -Rfp $mos/web/* /tmp/www/
	fi
	echo "Done"
	;;
  stop)
	echo "Stopping core..."
	if [ -d /tmp/www/mos ] ; then
		echo "  Remove files..."
		rm -Rf /tmp/www/mos
		rm -f /tmp/www/cgi-bin/services.cgi
		[ -f /tmp/www/WebTorrentHome.html ] && mv /tmp/www/WebTorrentHome.html /tmp/www/index.html
	fi
	echo "Done"
	;;
  enable)
	echo "Enabling core..."
	# patching anything
	if [ -f $mos/patch ] ; then
	  $mos/patch
	  rm $mos/patch
	fi

	echo "Patching AWK"
	ln -s $mos/awk /usr/local/etc/awk
#	if [ -z "$( cat /usr/local/etc/profile | grep 'pathmunge /usr/local/etc' )" ] ; then
#	  sed -i '
#	    /pathmunge \/sbin/i\
#	    pathmunge /usr/local/etc
#	' /usr/local/etc/profile
#	fi
	
	
	echo "Copying wakeup script..."
	cp $mos/wakeup /usr/local/etc/
	
	echo "patching rcS..."
	if [ -z "$( cat /usr/local/etc/rcS | grep '/usr/local/etc/wakeup' )" ] ; then
	  echo "Adding start services to rcS..."
	  echo "/usr/local/etc/wakeup" >> /usr/local/etc/rcS
	fi
	#cleanup previous install
	if [ ! -z "$( cat /usr/local/etc/rcS | grep '/usr/local/etc/mos/services start' )" ] ; then
#	  echo "Adding start services to rcS..."
#	  echo "/usr/local/etc/mos/services start" >> /usr/local/etc/rcS
	sed -i '/\/usr\/local\/etc\/mos\/services start/d' /usr/local/etc/rcS
	fi

	if [ -f /usr/local/bin/scripts/news.rss ] ; then

	  echo "adding RSS..."
	  if [ ! -f $spa/news.rss ] ; then
	    mkdir -p $spa
	    cp /usr/local/bin/scripts/news.rss $spa/
	  fi

	  if [ ! -f /usr/local/etc/moMenu.rss ] ; then
	    cp $mos/rss/moMenu.rss /usr/local/etc/
	  fi

	  if [ -z "$( cat $spa/news.rss | grep moMenu.rss )" ] ; then
	    sed -i '
/<title>\$\[RSS_NEWS_ADD_RSS_URL\]<\/title>/i\
		<title>Additional services</title>\
		<link>rss_file://../etc/moMenu.rss</link>\
		<media:thumbnail url="/usr/local/etc/mos/core/rss/moMenu.png" width="120" height="90" />\
	</item>\
	<item>
' $spa/news.rss
	  fi
	fi
	echo "Done"
	;;
  disable)
	echo "Disabling core..."
	echo "unpatching rcS..."
	if [ ! -z "$( cat /usr/local/etc/rcS | grep '/usr/local/etc/wakeup' )" ] ; then
	  echo "Remove start services from rcS..."
	  sed -i '/\/usr\/local\/etc\/wakeup/d' /usr/local/etc/rcS
	fi
		# Remove from RSS
	echo "Remove RSS..."
	sed -i '
	/<title>Additional services<\/title>/{N;N;N;N;d}
	' $momenu
	
	sed -i '/pathmunge \/usr\/local\/etc/d' /usr/local/etc/profile

	rm -f /usr/local/etc/awk
	rm -f /usr/local/etc/wakeup
	echo "Done"
	;;
  restart | status)
	;;
  *)
	echo "Usage: $0 {start|stop|restart|status|enable|disable}"
esac

exit $?
